//
//  SKXRongCloudManager.m
//  RongCloudDemo
//
//  Created by songKX on 16/3/9.
//  Copyright © 2016年 songKX. All rights reserved.
//

#import "SKXRongCloudManager.h"

#import <CommonCrypto/CommonDigest.h>
#import "PlayerManager.h"


@interface SKXRongCloudManager ()<AVAudioRecorderDelegate>

@property (nonatomic,strong) AVAudioRecorder *audioRecorder;//音频录音机

@property (nonatomic,strong) AVAudioPlayer *audioPlayer;//音频播放器，用于播放录音文件

@end

static SKXRongCloudManager *manager = nil;

static NSURL *filePath = nil;

@implementation SKXRongCloudManager



+(instancetype)sharaManager{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        manager = [[SKXRongCloudManager alloc] init];
        
        
    });
    
    return manager;
}


+(void) getTokenSuccessWithUsername:(NSString *)userName NickName:(NSString *)nickName :(void (^)(id response))success
                            failure:(void (^)(NSError* err))failure{
    
    
//    App-Key 或 RC-App-Key	String	开发者平台分配的 App Key。
//    Nonce或 RC-Nonce	String	随机数，无长度限制。
//    Timestamp 或 RC-Timestamp	String	时间戳，从 1970 年 1 月 1 日 0 点 0 分 0 秒开始到现在的秒数。
//    Signature 或 RC-Signature	String	数据签名。

    
//    
    
//
    
    
    //POST请求 请求参数放在请求内部(httpBody)
    //设置请求
    NSMutableURLRequest * request = [[NSMutableURLRequest alloc] init];
    request.timeoutInterval = 10;
    request.HTTPMethod = @"POST";
    request.URL = [NSURL URLWithString:@"https://api.cn.ronghub.com/user/getToken.json"];
    
    NSString * appkey = @"pgyu6atqylt4u";
    NSString * nonce = [NSString stringWithFormat:@"%d",arc4random()];
    NSString * timestamp = [[NSString alloc] initWithFormat:@"%ld",(NSInteger)[NSDate timeIntervalSinceReferenceDate]];
    
    //配置http header
    [request setValue:appkey forHTTPHeaderField:@"App-Key"];
    [request setValue:nonce forHTTPHeaderField:@"Nonce"];
    [request setValue:timestamp forHTTPHeaderField:@"Timestamp"];
    [request setValue:@"8ESiyL60ULTC" forHTTPHeaderField:@"appSecret"];
    //生成hashcode 用以验证签名
//    [request setValue:[self sha1:[NSString stringWithFormat:@"%@%@%@",appkey,nonce,timestamp]] forHTTPHeaderField:@"Signature"];
//    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    
    NSMutableDictionary * paramDic = [NSMutableDictionary dictionary];
    [paramDic setObject:userName forKey:@"userId"];
    [paramDic setObject:nickName forKey:@"name"];
    [paramDic setObject:@"http://c.hiphotos.baidu.com/zhidao/wh%3D450%2C600/sign=c4a97118d3160924dc70aa1fe13719cc/f11f3a292df5e0feeb719f4f5f6034a85edf7216.jpg" forKey:@"portraitUri"];
    
    request.HTTPBody = [self httpBodyFromParamDictionary:paramDic];
    
    NSURLSession *session = [NSURLSession sharedSession];
    
    NSURLSessionDataTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
       
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSLog(@"%@",dic);
        
        failure(error);
        
    }];
    [task resume];
    
}

//拼接字串
+ (NSData *)httpBodyFromParamDictionary:(NSDictionary *)param
{
    NSMutableString * data = [NSMutableString string];
    for (NSString * key in param.allKeys) {
        [data appendFormat:@"%@=%@&",key,param[key]];
    }
    return [[data substringToIndex:data.length-1] dataUsingEncoding:NSUTF8StringEncoding];
}


//  哈希计算
+ (NSString *) sha1:(NSString *)input
{
    NSData *data = [input dataUsingEncoding:NSUTF8StringEncoding];
    
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    
    CC_SHA1(data.bytes, (unsigned int)data.length, digest);
    
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH *2];
    
    for(int i=0; i<CC_SHA1_DIGEST_LENGTH; i++) {
        [output appendFormat:@"%02x", digest[i]];
    }
    return output;
}



#pragma mark ------ 录音的实现-------

//录制声音

-(void)setAudioSession{
    AVAudioSession *audioSession=[AVAudioSession sharedInstance];
    //设置为播放和录音状态，以便可以在录制完之后播放录音
    [audioSession setCategory:AVAudioSessionCategoryRecord error:nil];
    [audioSession setActive:YES error:nil];
}


-(void)SkxStartRecord{
    
    if (![self.audioRecorder isRecording]) {
        [self.audioRecorder record];//首次使用应用时如果调用record方法会询问用户是否允许使用麦克风
        
    }
    
}

-(void)SkxStopRecord:(void (^)(NSURL * url))success{
    
    [self.audioRecorder stop];
    
    NSLog(@"%@",filePath);
    
    success(filePath);
    
}

//获取录音保存路径

-(NSURL *)getSavePath{
    
    int x = arc4random() % 100000;
    NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
    NSString *fileName = [NSString stringWithFormat:@"%d%d.caf",(int)time , x];
    
    NSString *urlStr=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    urlStr=[urlStr stringByAppendingPathComponent:fileName];
    NSLog(@"file path:%@",urlStr);
    NSURL *url=[NSURL fileURLWithPath:urlStr];
    
    filePath = url;
    
    return url;
}

//设置录音格式

-(NSDictionary *)getAudioSetting{
    NSMutableDictionary *dicM=[NSMutableDictionary dictionary];
    //设置录音格式（mp3）
    [dicM setObject:@(kAudioFormatLinearPCM) forKey:AVFormatIDKey];
    //设置录音采样率，8000是电话采样率，对于一般录音已经够了
    [dicM setObject:@(8000) forKey:AVSampleRateKey];
    //设置通道,这里采用单声道
    [dicM setObject:@(1) forKey:AVNumberOfChannelsKey];
    //每个采样点位数,分为8、16、24、32
    [dicM setObject:@(8) forKey:AVLinearPCMBitDepthKey];
    //是否使用浮点数采样
    [dicM setObject:@(YES) forKey:AVLinearPCMIsFloatKey];
    //....其他设置等
    return dicM;
}


-(AVAudioRecorder *)audioRecorder{
    if (!_audioRecorder) {
        
        //创建录音文件保存路径
        NSURL *url=[self getSavePath];
        //创建录音格式设置
        NSDictionary *setting=[self getAudioSetting];
        //创建录音机
        NSError *error=nil;
        _audioRecorder=[[AVAudioRecorder alloc]initWithURL:url settings:setting error:&error];
        _audioRecorder.delegate=self;
        if (error) {
            NSLog(@"创建录音机对象时发生错误，错误信息：%@",error.localizedDescription);
            return nil;
        }
    }
    return _audioRecorder;
}

/**
 *  创建播放器
 *
 *  @return 播放器
 */

-(void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag{
    
    if (flag) {
        
        
        
        NSLog(@"录音成功");
        
    }
    
    
}

//音频播放

-(void)SkxPlayRecordWith:(NSURL *)filePath{
    
    NSError *error = nil;
    
    [_audioPlayer stop];

    _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:filePath error:&error];
    
    _audioPlayer.numberOfLoops=0;
    
    [_audioPlayer prepareToPlay];
    
    if (!error) {
        NSLog(@"播放成功");
        
        [_audioPlayer play];
        
    }else{
        
        NSLog(@"播放失败");
    }    
}

-(void)skxStopPlay{
    
    [_audioPlayer stop];
    _audioPlayer = nil;
    
}

-(void)playRecordSuccessWithURL:(NSString *)url{
//    播放录音，播放器暂停
    [[PlayerManager defaultManager] pausePlay];
   
AVFile *file =[AVFile fileWithURL:url];
[file getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
    NSString *path =  [file localPath];
    NSLog(@"%@",path);
    [data writeToFile:path atomically:YES];
    [SKXFriendManager playVoiceWith:path WithLabel:nil];
    }];
}

@end
